import React from 'react';
import { Tabs, Table } from 'antd';
import type { TabsProps } from 'antd';
import { Card } from 'antd';
import StockChart from '../../components/stockChart6';
import TickChart from '../../components/TickChart.jsx';
import TickKlineChart from '../../components/TickKlineChart.jsx';
import { fetchStockEnergyZtData,StockZtData,fetchStockMinuteDataByCode,StockMinuteData,fetchStockKDataByCode,StockKData,fetchStockInfoByCode,StockInfoData } from '../../services/review.ts';
import './EnergyCenter.css';
import KLineChart from '../../components/KLineChart.jsx';


interface StockData {
  minute: Array<[string, number, number]>;
  minute5: Array<[string, number, number]>;
  daily: Array<[string, number, number, number, number, number, number, number, number, number]>;
  weekly: Array<[string, number, number, number, number, number, number, number, number, number]>;
  monthly: Array<[string, number, number, number, number, number, number, number, number, number]>;
}



const EnergyCenter: React.FC = () => {
  const [tickDataSource, setTickDataSource] = React.useState<StockZtData[]>();
  const [stockTickData, setStockTickData] = React.useState<StockMinuteData[]>();
  const [selectedStockCode, setSelectedStockCode] = React.useState<string | null>(null);
  const [selectedRowKey, setSelectedRowKey] = React.useState<string | null>(null);
  const [isDataLoaded, setIsDataLoaded] = React.useState(false);
  const [dailyKData, setDailyKData] = React.useState<StockKData[]>([]);
  const [weeklyKData, setWeeklyKData] = React.useState<StockKData[]>([]);
  const [monthlyKData, setMonthlyKData] = React.useState<StockKData[]>([]);
  const [stockInfoData, setStockInfoData] = React.useState<StockInfoData>();

  React.useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetchStockEnergyZtData();
        const latestDate = response.trade_date;
        const formattedData = response.stocks.map((item, index) => ({
          key: item.ts_code,
          ts_code: item.ts_code,
          name: item.name,
          close: item.close,
          pct_chg: item.pct_chg,
          amount: item.amount,
          turnover_rate_f: item.turnover_rate_f,
          circ_mv: item.circ_mv,
        }));
        setTickDataSource(formattedData);
        const default_code  = formattedData[0].ts_code;
        setSelectedStockCode(formattedData[0].ts_code);
        setSelectedRowKey(formattedData[0].ts_code);
        setIsDataLoaded(false);
        fetchStockMinuteDataByCode(default_code, "5")
            .then(data => {
              console.log('分时数据111:', data);
              setStockTickData(data);
              
            })
            .catch(error => {
              console.error('获取分时数据失败:', error);
              setIsDataLoaded(false);
            });
        //获取第一个个股的日K、周K和月K数据
        fetchStockKDataByCode(default_code, "day")
          .then(data => {
            setDailyKData(data);
          })
          .catch(error => {
            console.error('获取日K数据失败:', error);
          });
        fetchStockKDataByCode(default_code, "week")
          .then(data => {
            setWeeklyKData(data);
          })
          .catch(error => {
            console.error('获取周K数据失败:', error);
          });
        fetchStockKDataByCode(default_code, "month")
          .then(data => {
            setMonthlyKData(data);
          })
          .catch(error => {
            console.error('获取月K数据失败:', error);
          });
        fetchStockInfoByCode(default_code)
          .then(data => {
            setStockInfoData(data);
          })
          .catch(error => {
            console.error('获取股票信息失败:', error);
          });
        setIsDataLoaded(true);
      } catch (error) {
        console.error('Failed to fetch data:', error);
      }
    };
    
    fetchData();
  }, []);
  


  const Stockcolumns = [
    {
      title: '代码',
      dataIndex: 'ts_code',
      key: 'ts_code',
      width: 120,
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '涨幅',
      dataIndex: 'pct_chg',
      key: 'pct_chg',
      render: (text: number) => `${text.toFixed(2)}%`,
    },
    {
      title: '现价',
      dataIndex: 'close',
      key: 'close',
    },
    {
      title: '换手率',
      dataIndex: 'turnover_rate_f',
      key: 'turnover_rate_f',
      render: (text: number) => `${text.toFixed(2)}%`,
    },
    {
      title: '成交额',
      dataIndex: 'amount',
      key: 'amount',
      render: (text: number) => `${(text/100000).toFixed(2)}亿元`,
    },
    {
      title: '流通市值',
      dataIndex: 'circ_mv',
      key: 'circ_mv',
      render: (text: number) => `${(text/10000).toFixed(1)}亿元`,
    },
  ];

  const items: TabsProps['items'] = [
  {
    key: '1',
    label: '涨停以上',
    children: <Table 
      dataSource={tickDataSource} 
      columns={Stockcolumns}  
      className="dark-theme-table"
      rowClassName={(record) => record.ts_code === selectedRowKey ? 'selected-row' : ''}
      scroll={{ y: 600 }}
      pagination={false}
      onRow={(record) => ({
        onClick: () => {
          const code = record.ts_code;
          setSelectedRowKey(code);
          setSelectedStockCode(code);
          setIsDataLoaded(false); // 重置加载状态
            fetchStockMinuteDataByCode(code, "5")
              .then(data => {
                setStockTickData(data);
               
              })
              .catch(error => {
                console.error('获取分时数据失败:', error);
                setIsDataLoaded(false); // 失败时重置状态
              });
          
          // 获取日K数据
          fetchStockKDataByCode(code, "day")
            .then(data => {
              setDailyKData(data);
            })
            .catch(error => {
              console.error('获取日K数据失败:', error);
            });
          
          // 获取周K数据
          fetchStockKDataByCode(code, "week")
            .then(data => {
              setWeeklyKData(data);
            })
            .catch(error => {
              console.error('获取周K数据失败:', error);
            });
          
          // 获取月K数据
          fetchStockKDataByCode(code, "month")
            .then(data => {
              setMonthlyKData(data);
            })
            .catch(error => {
              console.error('获取月K数据失败:', error);
            });
          fetchStockInfoByCode(code)
          .then(data => {
            setStockInfoData(data);
          })
          .catch(error => {
            console.error('获取股票信息失败:', error);
          });
          setIsDataLoaded(true);
        },  
        })
      }
    />,
  },
  {
    key: '2',
    label: '新高',
    children: <Table dataSource={tickDataSource} columns={Stockcolumns} className="dark-theme-table" />,
  },
];


  return (
    <div className="page-content">
      {/* 上方区域：涨停新高复盘 */}
      <Card title="涨停新高复盘" bordered={false} headStyle={{ color: '#ffffff', borderBottom: 'none' }} style={{ marginBottom: '24px !important', backgroundColor: '#112240', color: '#ccd6f6', borderColor: '#233554' }}>
        <div className="section-content" style={{ display: 'flex', gap: '16px' }}>
          <div className="left-panel" style={{ flex: 1, width:'40%' }}>
            <Tabs defaultActiveKey="1" items={items} tabBarStyle={{ fontSize: '26px', color: '#ffffff !important', fontWeight: 'bold' }} />
          </div>
          <div className="right-panel" style={{ flex: 1, width:'60%' }}>
            { 
            // <StockChart stockCode={selectedStockCode} dayKdata = {dailyKData} weekKdata = {weeklyKData}
            //     monthKdata={monthlyKData} tickData={stockTickData} infoData = {stockInfoData} isDataLoaded={isDataLoaded} />
            // }
            <TickKlineChart dayKdata = {dailyKData} weekKdata = {weeklyKData}
                monthKdata={monthlyKData} tickData={stockTickData} infoData = {stockInfoData} />
            }
            {/* <TickChart tickData={stockTickData} isDataLoaded={isDataLoaded}  /> */}
            {/* <KLineChart data = {dailyKData} symbol={selectedStockCode || ''} /> */}
          </div>
        </div>
      </Card>

      {/* 中间区域：属性归类 */}
      <Card title="属性归类" bordered={false} headStyle={{ color: '#ffffff', borderBottom: 'none' }} style={{ marginBottom: '24px !important', backgroundColor: '#112240', color: '#ccd6f6', borderColor: '#233554' }}>
        <div className="table-container">
          <Table 
            columns={[
              { title: '属性名称', dataIndex: 'name', key: 'name' },
              { title: '属性值', dataIndex: 'value', key: 'value' },
              { title: '分类', dataIndex: 'category', key: 'category' },
            ]}
            dataSource={[
              { key: '1', name: '市盈率', value: '15.2', category: '估值指标' },
              { key: '2', name: '市净率', value: '2.1', category: '估值指标' },
              { key: '3', name: 'ROE', value: '12.5%', category: '盈利能力' },
            ]}
            className="dark-theme-table"
          />
        </div>
      </Card>

      {/* 下方区域：位置量价与模型分析 */}
      <Card title="位置量价与模型分析" bordered={false} headStyle={{ color: '#ffffff', borderBottom: 'none' }} style={{ marginBottom: '24px !important', backgroundColor: '#112240', color: '#ccd6f6', borderColor: '#233554' }}>
        <div className="table-container">
          <Table 
            columns={[
              { title: '指标名称', dataIndex: 'name', key: 'name' },
              { title: '当前值', dataIndex: 'value', key: 'value' },
              { title: '模型分析', dataIndex: 'analysis', key: 'analysis' },
            ]}
            dataSource={[
              { key: '1', name: '成交量', value: '2000', analysis: '放量突破' },
              { key: '2', name: '价格位置', value: '高位', analysis: '需警惕回调' },
              { key: '3', name: 'MACD', value: '金叉', analysis: '短期看涨' },
            ]}
            className="dark-theme-table"
          />
        </div>
      </Card>
    </div>
  );
};

export default EnergyCenter;